/*
一、进制转换
二、生成自用编号
*/

package conversion

import (
	"math"
	"strconv"
	"strings"
	"time"
)

// 转换对应表
var tenToAny map[int]string = map[int]string{0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9",
	10: "a", 11: "b", 12: "c", 13: "d", 14: "e", 15: "f", 16: "g", 17: "h", 18: "i", 19: "j", 20: "k", 21: "l", 22: "m", 23: "n", 24: "o", 25: "p", 26: "q", 27: "r", 28: "s", 29: "t", 30: "u", 31: "v", 32: "w", 33: "x", 34: "y", 35: "z",
	36: "A", 37: "B", 38: "C", 39: "D", 40: "E", 41: "F", 42: "G", 43: "H", 44: "I", 45: "J", 46: "K", 47: "L", 48: "M", 49: "N", 50: "O", 51: "P", 52: "Q", 53: "R", 54: "S", 55: "T", 56: "U", 57: "V", 58: "W", 59: "X", 60: "Y", 61: "Z"}

// 根据VALUE找KEY
func findKey(in string) int {
	res := -1
	for k, v := range tenToAny {
		if in == v {
			res = k
		}
	}
	return res
}

// 十进制转任意
func decimalToAny(num int) string {
	new_num_str := ""
	var remainder int
	var remainder_str string
	n := len(tenToAny)

	for num != 0 {
		remainder = num % n
		if n > remainder && remainder > 9 {
			//n~9之间查询
			remainder_str = tenToAny[remainder]
		} else {
			//0~9之间直接转换为字符串格式
			remainder_str = strconv.Itoa(remainder)
		}
		new_num_str = remainder_str + new_num_str
		num = num / n
	}

	return new_num_str
}

// 任意转十进制
func anyToDecimal(num_str string) int {
	var new_num, tmp float64 = 0.0, 0.0
	nNum := len(strings.Split(num_str, "")) - 1
	n := len(tenToAny)

	for _, value := range strings.Split(num_str, "") {
		tmp = float64(findKey(value))
		if tmp != -1 {
			new_num = new_num + tmp*math.Pow(float64(n), float64(nNum))
			nNum = nNum - 1
		} else {
			break
		}
	}

	return int(new_num)
}

// TODO: 由当前时间取编号
func GetNumber() string {
	millisecond_stamp := time.Now().UnixNano() / 1e6
	//println(millisecond_stamp)
	s := decimalToAny(int(millisecond_stamp))
	s = "KL_" + s
	return s
}

// TODO: 由编号取时间
func GetTime(in_str string) string {
	str := in_str[3:]
	println(str)
	timestamp := anyToDecimal(str)
	//println(timestamp)
	timeobj := time.Unix(0, int64(timestamp*1e6))
	date_time := timeobj.Format("2006-01-02 15:04:05.000")
	return date_time
}
